﻿#region directives

using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using Toodledo.Model;
using Toodledo.Model.API;

#endregion

namespace Toodledo.Client
{
    public partial class Session : IGeneral
    {
        #region Implementation of IGeneral

        IEnumerable<Folder> IGeneral.GetFolders()
        {
            ItemFactory<Folder> factory = new ItemFactory<Folder>("folder")
                .Element<int>("Id", "id")
                .Element<bool>("IsPrivate", "private")
                .Element<bool>("IsArchived", "archived")
                .Element<int>("Order", "order")
                .Element<string>("Name", "name");


            List<Folder> results = new List<Folder>();

            XDocument response = SendRequest(ActionTypes.GetFolders);
            foreach (XElement thisElement in response.Descendants(XName.Get("folder", "")))
                results.Add(factory.Create(thisElement));

            return results;
        }


        int IGeneral.AddFolder(string title, bool isPrivate)
        {
            string parameters = FormatArgument(title, "name") + FormatArgument(isPrivate, "private");
            XDocument response = SendRequest(ActionTypes.AddFolder, parameters);
            XElement folder = response.Descendants(XName.Get("folder", "")).FirstOrDefault();
            return ReadElement<int>(folder, "id");
        }


        int IGeneral.EditFolder(Folder folder)
        {
            string parameters = FormatArgument(folder.Name, "name") + FormatArgument(folder.Id, "id");
            XDocument response = SendRequest(ActionTypes.EditFolder, parameters);
            XElement f = response.Descendants(XName.Get("folder", "")).FirstOrDefault();
            return ReadElement<int>(f, "id");
        }


        bool IGeneral.DeleteFolder(int id)
        {
            string parameters = FormatArgument(id, "id");
            XDocument response = SendRequest(ActionTypes.DeleteFolder, parameters);
            //todo test for error's
            return response != null ? ReadElement<int>(response) == id : false;
        }

        #endregion
    }
}